package server.world

//Class or object that handles the Turn Loop. Processes actions per location and Global world changes. 

import scala.util.Sorting
import scala.collection.mutable.Stack
import server.world.action._
import server.world.character._

object TurnProcessor{
	private var turnN:Int = 0 //turn count since the start
	private var actionList:Stack[Action] = Stack()  
  private var charList:List[GameCharacter] = List()

def processTurn{
	AI.giveComands
  
	for(action<-actionList){action.tick}
  
  if(!actionList.isEmpty)do{
    
		for(action<-actionList){ action.checkpredicate}
		actionList = actionList.sortBy { x => x.ap }
    
		if(!actionList.isEmpty && actionList(0).ap <= 0){
     val executedAction = actionList.pop
     executedAction.exe()
     executedAction.char.actionPending = false
    }
	} while(!actionList.isEmpty && actionList(0).ap <= 0)
    
  for(char <- charList){
    if(!char.isAlive()) killCharacter(char)
  }
    
		turnN = turnN+1
}

def killCharacter(char:GameCharacter){
  removeCharacter(char)
  removeCharacterAction(char)
  char.tile = null
  
  if(char.isInstanceOf[NPC]) AI.removeNPC(char.asInstanceOf[NPC])
}

def removeCharacter(char:GameCharacter){
  def pred(e1:GameCharacter):Boolean = (e1 != char)
  charList = charList.filter(pred)
}

def removeAction(act:Action){ 
  def pred(e1:Action):Boolean = (e1 != act)
      actionList = actionList.filter(pred)
      act.char.actionPending = false
}
  
def removeCharacterAction(character:GameCharacter){ 
	def pred(e1:Action):Boolean = (e1.char != character)
			actionList = actionList.filter(pred)
      character.actionPending = false
}

def addCharacter(char:GameCharacter){
  charList = char :: charList
}
def addAction(action:Action){
  if(action.char.isabletoAct & action.char.skillbook.contains(action.skillname)){
  actionList.push(action)
  action.char.actionPending = true
  }
  
}


//methods to allow reading private variables
def getActionStack() = actionList
def getCharList() = charList
def getTurn() = turnN

def flush(){ // reset the vars required for testing
  turnN = 0 
  actionList= Stack()  
  charList = List()
  AI.NPCList = List()
}

}